﻿using NetworkUI;
using Red.Controls.Diagrams.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Red.Controls.Diagrams
{
    class NodeDragger
    {
        #region Data

        private readonly NetworkView _networkView;
        private readonly IEnumerable<Tuple<double, double, string, NodeViewModel>> _nodesDataTuple;

        #endregion Data

        #region Events

        internal delegate void FinishedEventHandler( NodeDragger sender, IEnumerable<Tuple<double, double, string, NodeViewModel>> nodesDataTuple );
        internal event FinishedEventHandler Finished;

        private void OnFinished()
        {
            if ( Finished != null )
                Finished( this, _nodesDataTuple );
        }

        #endregion Events

        #region C-tor

        public NodeDragger( NetworkView networkView, IEnumerable<NodeViewModel> nodes )
        {
            _networkView = networkView;

            _networkView = networkView;
            _networkView.NodeDragCompleted += NetworkView_NodeDragCompleted;
            _nodesDataTuple = CreateNodePositionList( nodes );
        }

        #endregion C-tor

        #region Private methods

        private IEnumerable<Tuple<double, double, string, NodeViewModel>> CreateNodePositionList( IEnumerable<NodeViewModel> nodes )
        {
            return nodes.Select( item => Tuple.Create( item.X, item.Y, item.ID, item ) ).ToList();
        }

        #endregion Private methods

        #region Event handlers

        void NetworkView_NodeDragCompleted( object sender, NodeDragCompletedEventArgs e )
        {
            _networkView.NodeDragCompleted -= NetworkView_NodeDragCompleted;
            OnFinished();
        }

        #endregion Event handlers
    }
}
